<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class CreateModelFromDBTable extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:model:from:dbtable';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '根据数据库表生成model文件';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $tables = \DB::select("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='".env('DB_DATABASE')."';");

        $perfix = env('DB_PREFIX');
        foreach ($tables as $t){
            $table = str_replace("{$perfix}", "", $t->TABLE_NAME);

            $tableWords = explode('_', $table);
            $modelName = '';
            foreach ($tableWords as $tw){
                $modelName .= ucfirst($tw);
            }

            if($modelName == '  Migrations'){
                continue;
            }

            $modelContent = <<<MODEL
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class {$modelName} extends Model{

    protected \$table = '{$table}';
    public \$timestamps = false;
}

MODEL;
            if(!file_exists(app_path()."/Models/{$modelName}.php")) {
                file_put_contents(app_path() . "/Models/{$modelName}.php", $modelContent);
                echo "创建{$modelName}.php\n";
            }else{
                echo "{$modelName}.php已存在\n";
            }
        }
    }
}
